<template>
  <div>
    <el-upload class="upload-demo" :file-list="videoList" :action="$config.upload_url" :on-success="handleVideoSuccess" :on-remove="videoRemove" :before-upload="beforeUploadVideo">
      <div class="flex mt10">
        <div>
          <el-button size="small" type="primary">点击上传</el-button>
          <div slot="tip" class="el-upload__tip">只能上传视频文件</div>
        </div>
      </div>
    </el-upload>
    <div class="mt10">
      <el-input type="textarea" :row="{min:4}" v-model="currentSection.video" @input="result" placeholder="使用上传视频请等待视频上传成功后自动填写该项"></el-input>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      currentSection: {},
      videoList: [] // 视频回显数组
    }
  },
  methods: {
    // 视频上传成功
    handleVideoSuccess(e, file, fileList) {
      if (e.code === 0) {
        this.videoList = [{
          name: file.name
        }]
        this.currentSection.video = e.url
        this.currentSection.duration = e.minute
		this.result()
      } else {
        this.$message.error(e.msg)
      }
    },
    result() {
      this.$emit('change', this.currentSection)
    },
    // 视频列表移除文件
    videoRemove(e, fileList) {
      if (fileList.length <= 0) {
        this.currentSection.video = ''
        this.currentSection.duration = 0
      }
	  this.result()
    },
    // 视频上传前回调
    beforeUploadVideo(file) {
      if (['video/mp4', 'video/ogg', 'video/flv', 'video/avi', 'video/wmv', 'video/rmvb', 'video/mov'].indexOf(file.type) ==
        -1) {
        this.$message({
          message: '请上传正确的视频格式',
          type: 'warning'
        })
        return false
      } else {
        // 获取视频时长
        let url = URL.createObjectURL(file)
        let audioElement = new Audio(url)
        let duration
        audioElement.addEventListener('loadedmetadata', function (_event) {
          duration = audioElement.duration // 时长为秒，小数，182.36
        })
      }
    }
  }
}
</script>

<style lang='scss' scoped>
.mt10 {
  margin-top: 10px;
}
.flex {
  display: flex;
}
</style>
